package com.example.esp8266.Equipment.Equipment_Fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.esp8266.Equipment.Fragment_CallBack;
import com.example.esp8266.R;


import java.util.Objects;

public class Relay_Fragment extends Fragment
        implements View.OnClickListener{
    private View root;
    private ImageView relay1, relay2, relay3, relay4;
    private String target_device,back_info;
    private boolean Device_1_Status = false, Device_2_Status = false, Device_3_Status = false, Device_4_Status = false;
    private Fragment_CallBack callback;
    private TextView status_1,status_2,status_3,status_4;
    private int states = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            target_device = args.getString("target_device", "");//目标控制设备
            back_info = args.getString("back_info","");//返回上一层标识
        }

        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            Device_1_Status = sharedPreferences.getBoolean("Relay_1_Status", false);
            Device_2_Status = sharedPreferences.getBoolean("Relay_2_Status", false);
            Device_3_Status = sharedPreferences.getBoolean("Relay_3_Status", false);
            Device_4_Status = sharedPreferences.getBoolean("Relay_4_Status", false);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("previous_page",back_info);
            editor.apply();
        } else {
            Log.e("Relay_Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Fragment_CallBack) {
            callback = (Fragment_CallBack) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement Fragment_CallBack");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.relay_control_fragment, container, false);

        View btn8 = root.findViewById(R.id.relay_xml_btn8);
        btn8.setOnClickListener(this);

        View btn9 = root.findViewById(R.id.relay_xml_btn9);
        btn9.setOnClickListener(this);

        View btn1 = root.findViewById(R.id.relay_xml_btn1);
        btn1.setOnClickListener(this);

        View btn2 = root.findViewById(R.id.relay_xml_btn2);
        btn2.setOnClickListener(this);

        View btn3 = root.findViewById(R.id.relay_xml_btn3);
        btn3.setOnClickListener(this);

        View btn4 = root.findViewById(R.id.relay_xml_btn4);
        btn4.setOnClickListener(this);

        relay1 = root.findViewById(R.id.img_relay1);
        relay2 = root.findViewById(R.id.img_relay2);
        relay3 = root.findViewById(R.id.img_relay3);
        relay4 = root.findViewById(R.id.img_relay4);

        status_1 = root.findViewById(R.id.relay1_state_text);
        status_2 = root.findViewById(R.id.relay2_state_text);
        status_3 = root.findViewById(R.id.relay3_state_text);
        status_4 = root.findViewById(R.id.relay4_state_text);


        if(Device_1_Status){
            status_1.setText("开");
            status_1.setTextColor(Color.parseColor("#00FA9A"));
            relay1.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
        }
        if(Device_2_Status){
            status_2.setText("开");
            status_2.setTextColor(Color.parseColor("#00FA9A"));
            relay2.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
        }
        if(Device_3_Status){
            status_3.setText("开");
            status_3.setTextColor(Color.parseColor("#00FA9A"));
            relay3.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
        }
        if(Device_4_Status){
            status_4.setText("开");
            status_4.setTextColor(Color.parseColor("#00FA9A"));
            relay4.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
        }
        
        return root;
    }

    @Override//调用OnClickListener接口处理各种单击事件
    public void onClick(View v) {
        if (v.getId() == R.id.relay_xml_btn8){
            if (Objects.equals(back_info, "MainControlFragment")){
                // 检查 getActivity() 是否返回的对象为非空
                if (getActivity() != null) {
                    // 获取 SharedPreferences 对象
                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("previous_page",null);
                    editor.apply();
                } else {
                    Log.e("Fragment", "getActivity() returned null");
                    // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
                }
                MainControl_Fragment mainControlFragment = new MainControl_Fragment();
                replaceFragment(mainControlFragment);
            }
        }
        else if (v.getId() == R.id.relay_xml_btn9) {  // 切换功能场景
            states ++;
            if (states == 3) states = 0;
            if (states == 0){
                TextView states_text = root.findViewById(R.id.relay_title_text);
                states_text.setText("设备功能-客厅");
            } else if (states == 1) {
                TextView states_text = root.findViewById(R.id.relay_title_text);
                states_text.setText("设备功能-卧室");
            } else if (states == 2) {
                TextView states_text = root.findViewById(R.id.relay_title_text);
                states_text.setText("设备功能-厨房");
            }
        }
        else if (v.getId() == R.id.relay_xml_btn1) {  // 继电器按钮1状态
            if (!Device_1_Status) {
                String message_1 = callback.getMsgFromActivity("Request Message");
                if (message_1 != null && (message_1.contains("offline") || message_1.contains("busy"))) {
                    return;
                }
                Device_1_Status = true;
                status_1.setText("开");
                status_1.setTextColor(Color.parseColor("#00FA9A"));
                relay1.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
                if (states == 0) {
                    sendMessageToActivity("Relay1(True).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay1(True).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay1(True).100");
                }
            } else {
                String message_1 = callback.getMsgFromActivity("Request Message");
                if (message_1 != null && (message_1.contains("offline") || message_1.contains("busy"))) {
                    return;
                }
                Device_1_Status = false;
                status_1.setText("关");
                status_1.setTextColor(Color.parseColor("#FF0022"));
                relay1.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_off));
                if (states == 0) {
                    sendMessageToActivity("Relay1(False).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay1(False).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay1(False).100");
                }
            }
        }
        else if (v.getId() == R.id.relay_xml_btn2) {  // 继电器按钮2状态
            if (!Device_2_Status) {
                String message_2 = callback.getMsgFromActivity("Request Message");
                if (message_2 != null && (message_2.contains("offline") || message_2.contains("busy"))) {
                    return;
                }
                Device_2_Status = true;
                status_2.setText("开");
                status_2.setTextColor(Color.parseColor("#00FA9A"));
                relay2.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
                if (states == 0) {
                    sendMessageToActivity("Relay2(True).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay2(True).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay2(True).100");
                }
            } else {
                String message_2 = callback.getMsgFromActivity("Request Message");
                if (message_2 != null && (message_2.contains("offline") || message_2.contains("busy"))) {
                    return;
                }
                Device_2_Status = false;
                status_2.setText("关");
                status_2.setTextColor(Color.parseColor("#FF0022"));
                relay2.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_off));
                if (states == 0) {
                    sendMessageToActivity("Relay2(False).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay2(False).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay2(False).100");
                }
            }
        }
        else if (v.getId() == R.id.relay_xml_btn3) {  // 继电器按钮3状态
            if (!Device_3_Status) {
                String message_3 = callback.getMsgFromActivity("Request Message");
                if (message_3 != null && (message_3.contains("offline") || message_3.contains("busy"))) {
                    return;
                }
                Device_3_Status = true;
                status_3.setText("开");
                status_3.setTextColor(Color.parseColor("#00FA9A"));
                relay3.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
                if (states == 0) {
                    sendMessageToActivity("Relay3(True).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay3(True).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay3(True).100");
                }
            } else {
                String message_3 = callback.getMsgFromActivity("Request Message");
                if (message_3 != null && (message_3.contains("offline") || message_3.contains("busy"))) {
                    return;
                }
                Device_3_Status = false;
                status_3.setText("关");
                status_3.setTextColor(Color.parseColor("#FF0022"));
                relay3.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_off));
                if (states == 0) {
                    sendMessageToActivity("Relay3(False).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay3(False).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay3(False).100");
                }
            }
        } else if (v.getId() == R.id.relay_xml_btn4) {  // 继电器按钮4状态
            if (!Device_4_Status) {
                String message_4 = callback.getMsgFromActivity("Request Message");
                if (message_4 != null && (message_4.contains("offline") || message_4.contains("busy"))) {
                    return;
                }
                Device_4_Status = true;
                status_4.setText("开");
                status_4.setTextColor(Color.parseColor("#00FA9A"));
                relay4.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_on));
                if (states == 0) {
                    sendMessageToActivity("Relay4(True).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay4(True).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay4(True).100");
                }
            } else {
                String message_4 = callback.getMsgFromActivity("Request Message");
                if (message_4 != null && (message_4.contains("offline") || message_4.contains("busy"))) {
                    return;
                }
                Device_4_Status = false;
                status_4.setText("关");
                status_4.setTextColor(Color.parseColor("#FF0022"));
                relay4.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.relay_off));
                if (states == 0) {
                    sendMessageToActivity("Relay4(False).001");
                } else if (states == 1) {
                    sendMessageToActivity("Relay4(False).010");
                } else if (states == 2) {
                    sendMessageToActivity("Relay4(False).100");
                }
            }
        }
    }

    //动态切换视图
    private void replaceFragment(Fragment fragment){
        if (getActivity() != null) {
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.control_fragment_view, fragment);
            transaction.commit();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在离开 MainFragment 时
        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("Relay_1_Status",Device_1_Status);
            editor.putBoolean("Relay_2_Status",Device_2_Status);
            editor.putBoolean("Relay_3_Status",Device_3_Status);
            editor.putBoolean("Relay_4_Status",Device_4_Status);
            editor.apply();
        } else {
            Log.e("Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }
        callback = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 在 Fragment 生命周期结束时执行的操作
        callback = null;
    }

    // 调用 callback 方法
    // 向Activity发数据
    private void sendMessageToActivity(String msg) {
        if (callback != null) {
            callback.sendMsgToActivity(msg);
        }
    }

    // 向Activity取数据
    private void receiveMessageFromActivity() {
        if (callback != null) {
            String message = callback.getMsgFromActivity("Request Message");
            Log.d("YourFragmentClass", "Message from Activity: " + message);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callback = null;
    }
}